package com.rtf.framework.dao.rule.phone;

import com.rtf.framework.common.exception.AppException;
import com.rtf.framework.common.support.dao.handler.AppBaseDataHandlerAdaptor;
import com.rtf.framework.common.util.UtilString;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.Table;
import java.util.Collection;

public class UniquePhoneDataHandler extends AppBaseDataHandlerAdaptor {

    @Autowired
    private UniquePhoneRecordDao uniquePhoneRecordDao;

    @Override
    public boolean support(Class<?> entityClass) {
        return UniquePhoneRecord.class.isAssignableFrom(entityClass);
    }

    @Override
    public <T> T preSaveHandler(T entity) {
        Table tableAnno = entity.getClass().getAnnotation(Table.class);
        if (tableAnno == null) {
            throw new AppException("当前类必须是jpa管理的类");
        }
        UniquePhoneRecord uniquePhoneRecord = (UniquePhoneRecord) entity;
        if (UtilString.isBlank(uniquePhoneRecord.getTelephone())) {
            throw new AppException("手机号不能为空");
        }

        //将手机号统一去除空字符，并进行裁剪
        uniquePhoneRecord.setTelephone(uniquePhoneRecord.getTelephone().trim().toLowerCase());

        int existNum = uniquePhoneRecordDao.queryExistCount(tableAnno.name(), uniquePhoneRecord.getTelephone(), null);
        if (existNum > 0) {
            throw new AppException("保存失败，已经存在相同手机号。");
        }

        return super.preSaveHandler(entity);
    }

    @Override
    public <T> T preUpdateHandler(T entity, Collection<String> updateFields) {
        Table tableAnno = entity.getClass().getAnnotation(Table.class);
        if (tableAnno == null) {
            throw new AppException("当前类必须是jpa管理的类");
        }

        UniquePhoneRecord uniquePhoneRecord = (UniquePhoneRecord) entity;

        if (UtilString.isNotBlank(uniquePhoneRecord.getTelephone())) {
            //将手机号统一去除空字符，并进行裁剪
            uniquePhoneRecord.setTelephone(uniquePhoneRecord.getTelephone().trim().toLowerCase());
            int existNum = uniquePhoneRecordDao.queryExistCount(tableAnno.name(), uniquePhoneRecord.getTelephone(), uniquePhoneRecord.getId());
            if (existNum > 0) {
                throw new AppException("更新失败，已经存在相同手机号。");
            }
        }

        return super.preUpdateHandler(entity, updateFields);
    }

}
